package entity;

import image.ImageCache;
import level.*;

/**
 * A representation of a sprite for each entity that will appear in the game. A sprite 
 * is responsible for handling collisions and deciding movement upon a set
 * of properties defined either eternally (ie boundaries, walls ...) or within
 * subclasses (eg. positon...).
 * 
 * @author Neil Cowzer
 */
public class Sprite extends Entity{
	/** total number of frames. */
	private /*@ non_null @*/ int maxFrames = 5;
	
	/** The current animation value of the lemming.*/
	private int animation;
	/*@	invariant 0 <= animation
	  				   animation >= maxFrames;
	 @*/
	
	/** Array of location of Images */
	protected String[] frames;
	/*@ invariant
		frames != null
		&&
		(\forall int i; 0 <= i && i < frames.length;
		; frames[i] != null &&
		frames[i].getParent() == this);
	@*/
	
	/**
	 * Create a new Sprite.
	 * 
	 * @param ref The Image which should be displayed.
	 * @param x The x-coordinate of the Sprite.
	 * @param y The y-coordinate of the Sprite.
	 * @param level The level which the Sprite exist in.
	 */
	/*@ requires ref != null && 0 <= x && 0 <= y;
	   	assignable level;
	   	ensures true;
	@*/
	public Sprite(String ref, int maxFrames, int x, int y){
		super(ref, x, y);
		this.maxFrames = maxFrames;
		frames = new String[maxFrames];
		
		// only exception to code standard!!!!!
		if (maxFrames > 1) 
			generateFrames(ref);
		
		animation = 1;	// intialise the animation
	}
	
	/**
	 * Update the image to display of the Sprite
	 */
	/*@ assignable animation;
	 	ensures 0 <= animation &&
	 				 animation >= maxFrames;
	@*/
	public void update(){
		if (animation < 3){
			img = ImageCache.getCache().getSprite(frames[++animation]);
			//System.out.println(animation);
		}else {
			animation = 1;
			update();
		}
	}
	
	/**
	 * Fill the frames array with the location(String reference) of the Image(s).
	 * 
	 * @param ref the relative location of the Images.
	 */
	//@ requires ref != null;
	private void generateFrames(String ref){
		// Split the scenes
		String[] strings = ref.split("[0-9]");
		
		for (int i = 0; i < maxFrames; i++){
			frames[i] = strings[0] + i + strings[1];
		}
	}
}
